<template>
  <div class="w_h_100">
    <div class="box">
      <div class="inlet">系统管理 > <span class="size">担保公司管理</span></div>
      <myform :fields="fields" :model="values" class="m_t_10" :options="options">
        <template v-slot:button>
          <el-button @click="resetting">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
        </template>
      </myform>
    </div>
    <div class="mytable m_t_10 ">
      <div class="d_f j_c_s_b a_i_c">
        <h4>公司明细列表</h4>
        <el-button type="primary" :icon="Plus" @click="addCompany" v-hasPerm="'addCompany'">新建公司</el-button>
      </div>
      <mytable :fields="tableFields" width="150" ref="tableRef" :values="values" api="companyListByPage" class="m_t_10"
        :isSelection="false">
        <template v-slot:status="{ row }">
          <el-switch v-model="row.status" :before-change="beforeStatus" @change="changeSwitch(row.id, row.status)"
            inline-prompt active-text="开" inactive-text="关" class="ml-2" :active-value="1" :inactive-value="2"
            style="--el-switch-on-color:#13ce66; " />
        </template>
        <template v-slot:operation="{ row }">
          <div class="d_f j_c_s_b">
            <span class="edit" @click="edit(row)" v-hasPerm="'editCompany'">编辑</span>
            <span class="edit" @click="resetPassword(row)" v-hasPerm="'resetCompany'">重置密码</span>
            <span class="error" @click="deleteOut(row)" v-hasPerm="'deleteCompany'">删除</span>
          </div>
        </template>
      </mytable>
    </div>
    <el-drawer v-model="show" :title="title" size="500px" direction="rtl" :before-close="handleClose">
      <div class="company">
        <myform :fields="addFields" ref="ruleFrom" :options="options" :model="model" :inline="false" labelPosition="top"
          :rules="rules" class="m_t_16"></myform>
      </div>
      <div class="d_f j_c_c">
        <el-button type="primary" @click="save" v-myRepeat>保存</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { companyType } from '../../../type/system'
import { Search, Plus } from '@element-plus/icons-vue'
import { copy, objectMatching } from '../../../utils/date'
import { Message } from '../../../utils/resetMessage'
import { ElMessageBox } from 'element-plus'
import { companyAdd, companyUpdate, companyDel, companyResetPwd, companyStatus } from '../../../api/system/company'
import { listNoTenantAll } from '../../../api/system/authority'
import { PHONE_REG } from '../../../utils/regular'
const values = {
  status: '',
  usci: '',
  name: '',
}
const model = {
  usci: '',//统一社会信用代码
  name: '',//公司名称
  empName: '',//公司联系人
  empMobile: '',//联系人电话
  findEmpMobile: '',//旧联系人电话
  empEmail: '',//邮箱
  roleCode: '',//角色权限
  id: 0,
}
export default defineComponent({
  name: '',
  setup() {
    const data: companyType = reactive({
      fields: [
        {
          label: "统一社会信用代码",
          prop: 'usci',
          placeholder: '请输入18位代码',
          type: 'input',
          labelWidth: '125px'
        },
        {
          label: "公司名称",
          prop: 'name',
          placeholder: '请输入公司名称',
          type: 'input',
          labelWidth: '96px'
        },
        {
          label: "公司状态",
          prop: 'status',
          placeholder: '请选择公司状态',
          type: 'select',
          bindLabel: 'name',
          bindValue: 'id',
        },
        {
          prop: 'button'
        }
      ],
      values: copy(values),
      options: {
        status: [
          {
            name: '开启',
            id: 1
          },
          {
            name: '关闭',
            id: 2
          },
        ],
        roleCode: [],
      },
      tableFields: [
        {
          prop: 'usci',
          label: '统一社会信用代码',
        },
        {
          prop: 'name',
          label: '公司名称',
        },
        {
          prop: 'empName',
          label: '联系人',
        },
        {
          prop: 'empMobile',
          label: '联系人电话',
        },
        {
          prop: 'empEmail',
          label: '公司邮箱',
        },
        {
          prop: 'roleName',
          label: '角色权限',
        },
        {
          prop: 'status',
          label: '公司状态',
        },
      ],
      title: '',
      show: false,
      model: copy(model),
      addFields: [
        {
          label: '统一社会信用代码',
          type: 'input',
          placeholder: '请输入',
          prop: 'usci',
          disabled: false,
        },
        {
          label: '公司名称',
          type: 'input',
          placeholder: '请输入',
          prop: 'name',
          maxlength: '60'
        },
        {
          label: '联系人',
          type: 'input',
          placeholder: '请输入',
          prop: 'empName',
          maxlength: '10'
        },
        {
          label: '联系人电话',
          type: 'number',
          placeholder: '请输入',
          prop: 'empMobile'
        },
        {
          label: '公司邮箱',
          type: 'input',
          placeholder: '请输入',
          prop: 'empEmail'
        },
        {
          label: "角色权限",
          prop: 'roleCode',
          placeholder: '请选择角色权限',
          type: 'select',
          bindLabel: 'roleName',
          bindValue: 'roleCode',
        },
      ],
      rules: {
        usci: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z]{18}$/, message: '请输入正确统一社会信用代码' }
        ],
        name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 2, max: 60, message: '公司名称长度2-60位', trigger: 'blur' },
        ],
        empName: [
          { required: true, message: '请输入公司联系人', trigger: 'blur' },
          { min: 2, max: 10, message: '公司联系人2-10位', trigger: 'blur' },
        ],
        // empMobile: [
        //   { required: true, message: '请输入联系人电话', trigger: 'blur' },
        //   { pattern: PHONE_REG, message: '请输入正确的电话格式' }
        // ],
        empEmail: [
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur', }
        ],
        roleCode: [
          { required: true, message: '请选择角色权限', trigger: 'change' },
        ],
      },
      tag:false,

    })
    onBeforeMount(() => {
      methods.getRoleList()
    })
    const tableRef = ref()
    const ruleFrom = ref()
    const methods = {
      getRoleList() {
        listNoTenantAll({}).then((res: any) => {
          data.options.roleCode = res.filter((item: any) => {
            return item.deleted == 0
          })
        })
      },
      //表格数据重置
      resetting() {
        data.values = copy(values)
        tableRef.value.resettingTable(data.values)
      },
      //列表根据筛选条件搜索
      searchFor() {
        tableRef.value.handleCurrentChange(1)
      },
      //关闭弹窗
      handleClose() {
        ElMessageBox.confirm(
          '当前信息将不再保存?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            ruleFrom.value.resetFields()//重置表单
            data.show = false
            data.model = copy(model)
          })
      },
      addCompany() {
        data.title = '新增公司'
        data.show = true
        data.addFields[0].disabled = false
      },
      // //添加公司跟修改公司保存按钮事件
      save() {
        ruleFrom.value.verification().then(() => {
          data.model.findEmpMobile = data.model.empMobile
          if (!data.model.id) {
            companyAdd(data.model).then(() => {
              Message({ type: 'success', message: '添加成功' })
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
              data.show = false//关闭弹窗
              ruleFrom.value.resetFields()//重置表单
              data.model = copy(model)//重置表单绑定数据
            })
          } else {
            companyUpdate(data.model).then(() => {
              Message({ type: 'success', message: '修改成功' })
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
              data.show = false//关闭弹窗
              ruleFrom.value.resetFields()//重置表单
              data.model = copy(model)//重置表单绑定数据
            })
          }
        })
      },
      //编辑公司信息
      edit(row: any) {
        data.model = objectMatching(row, data.model)
        data.model.findEmpMobile = copy(row.empMobile)
        data.title = '编辑公司'
        data.addFields[0].disabled = true
        data.show = true
      },
      deleteOut(row: any) {
        let val = `确认删除”${row.name}“`
        ElMessageBox.confirm(
          val,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
          }
        )
          .then(() => {
            companyDel({ id: row.id }).then(() => {
              Message({ type: 'success', message: '删除成功' })
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
            })
          })
      },
      beforeStatus(e){
        return new Promise((resolve, reject) => {
        if (confirm) {
            // 点击确认按钮时设置tags值
            data.tag = true
            return resolve(true)
        } else {
            return reject(false)
        }
    })
      },
      //公司的启用跟停用
      changeSwitch(id: string | number, status: number | string) {

        if (!data.tag) return
        companyStatus({ id: id, status: status }).then(() => {
          Message({ type: 'success', message: '操作成功' })
        })
      },
      //重置用户密码
      resetPassword(row: any) {
        let message = `确认重置“${row.name}”的密码为统一社会信用代码后6位？`
        ElMessageBox.confirm(
          message,
          '重置密码',
          {
            confirmButtonText: '确认重置',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            companyResetPwd({ id: row.usci }).then(() => {
              Message({ type: 'success', message: '重置成功' })
            })
          })
      },
    }
    return {
      ...toRefs(data),
      Search, Plus,
      ...methods, tableRef, ruleFrom
    }
  }
})
</script>
<style scoped lang='scss'>
.box {
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  height: 70px;
  padding: 10px 32px;
  margin-top: 10px;
}

.mytable {
  overflow-y: auto;
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px 32px;
  height: calc(100% - 125px);
}
</style>
<style lang="scss">
.company {
  height: calc(100% - 70px);
  overflow-y: auto;

  .el-input,
  .el-select {
    width: 100% !important;
  }
}
</style>